package com.webserver.controller;

import com.webserver.entity.User;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;

/*
    MVC模型
    M:model 模型层,指的是系统中的业务层,负责完成处理不同的业务操作
    V:view  视图层,用来为用户展现信息,比如我们的html页面
    C:controller 控制层,负责统一调度,协调不同的请求应当由那些业务处理,并将处理业务的结果交由
                 那个视图进行展示.

    我们这里的C实际上是耦合了MVC的所有功能,并没有真正分离
 */
public class UserController {
    //用于保存所有用户信息的目录
    private static File USER_DIR =new File("./users");
    static {
        if (!USER_DIR.exists()){
            USER_DIR.mkdirs();
        }
    }

    public void reg(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户注册");
        //1获取用户在表单上输入的信息
        String username =request.getParameter("username");
        String password =request.getParameter("password");
        String nickname =request.getParameter("nickname");
        String ageStr =request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);

        int age =Integer.parseInt(ageStr);
        //2将信息保存
        //用户名.obj
        User user =new User(username,password,nickname,age);
        File userFile =new File(USER_DIR,username+"obj");
        try(
                FileOutputStream fos =new FileOutputStream(userFile);
                ObjectOutputStream oos =new ObjectOutputStream(fos);
        ){
            //将USer对象序列化到文件中持久保存
            oos.writeObject(user);
            System.out.println("注册成功！");

            File file =new File("./webapps/myweb/reg_success.html");
            response.setContentFile(file);

        } catch (IOException e) {
            e.printStackTrace();
        }
        //3响应客户端注册结果的页面
        System.out.println("用户处理注册完毕!");
    }
    public void login(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始登录");
        String username =request.getParameter("username");
        String password =request.getParameter("password");
        File userFile =new File(USER_DIR,username+"obj");

        if (userFile.exists()){
            try {
                FileInputStream fis=new FileInputStream(userFile);
                ObjectInputStream ois=new ObjectInputStream(fis);
                User user=(User)ois.readObject();
                if ((username.equals(user.getUsername()))&&(password.equals(user.getPassword()))){
                    System.out.println("登录成功！");
                    File file =new File("./webapps/myweb/login_success.html");
                    response.setContentFile(file);
                }else {
                    File file =new File("./webapps/myweb/login_fail.html");
                    response.setContentFile(file);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }else {

        }
    }
}
